package com.guyaogg.gulimall.search.service.impl;

import com.guyaogg.common.to.es.SkuEsModel;
import com.guyaogg.gulimall.search.config.GulimallElasticSearchConfig;
import com.guyaogg.gulimall.search.constant.EsConstant;
import com.guyaogg.gulimall.search.service.ProductSaveService;
import com.guyaogg.gulimall.search.utils.EsUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 顾遥
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 保存到 es
        // 给 es 中建立索引。product，建立好映射关系

        // BulkRequest bulkRequest, RequestOptions options

        BulkRequest bulkRequest = new BulkRequest();
        skuEsModels.forEach(model -> {
            // 索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 指定 id
            indexRequest.id(model.getSkuId().toString());
            // 存数据
            EsUtils.sourceJson(model, indexRequest);
            bulkRequest.add(indexRequest);
        });
        // 给 es 中保存数据
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        // TODO 如果批量错误，
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        if(b){
            Set<Long> set = new HashSet<>(collect.size());
            collect.forEach(item -> set.add(Long.parseLong(item)));
            List<Long> collect1 = skuEsModels.stream().map(SkuEsModel::getSkuId).filter(item -> !set.contains(item)).collect(Collectors.toList());
            log.error("商品上架错误：{}",collect1);
        }
        log.info("商品上架成功：{}",collect);
        return b;

    }

}
